package com.qianxx.component.activity.list.side_bar;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.qianxx.component.R;
import com.qianxx.component.activity.base.BaseActivity;
import com.qianxx.viewlibrary.list.sidebar.CharacterParser;
import com.qianxx.viewlibrary.list.sidebar.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SideBarActivity extends BaseActivity {
    @BindView(R.id.edit_text)
    EditText edit_text;
    @BindView(R.id.list_view)
    ListView list_view;
    @BindView(R.id.sidr_bar)
    SideBar sidr_bar;
    @BindView(R.id.text_view)
    TextView text_view;

    //汉字转换成拼音的类
    CharacterParser characterParser = CharacterParser.getInstance();
    List<String> list = new ArrayList<>();
    SortAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_side_bar);
        ButterKnife.bind(this);

        initData();
        initView();
    }

    private void initData() {
        list.add("阿巴斯");
        list.add("奥迪");
        list.add("阿斯顿马丁");
        list.add("宝马");
        list.add("保时捷");
        list.add("奔驰");
        list.add("标致");
        list.add("别克");
        list.add("宾利");
        list.add("比亚迪");
        list.add("长安");
        list.add("大众");
        list.add("福特");
        list.add("海马");
        list.add("皇冠");
        list.add("江淮");
        list.add("捷豹");
        list.add("凯迪拉克");
        list.add("兰博基尼");
        list.add("劳斯莱斯");
        list.add("雷克萨斯");
        list.add("雷诺");
        list.add("力帆");
        list.add("路虎");
        list.add("迈巴赫");
        list.add("马自达");
        list.add("Mini");
        list.add("Nissan");
        list.add("奇瑞");
        list.add("起亚");
        list.add("现代");
        list.add("雪佛兰");
        list.add("雪铁龙");
        list.add("英菲尼迪");
        list.add("中兴");

        // 排序
        Collections.sort(list, new Comparator<String>() {

            @Override
            public int compare(String lhs, String rhs) {
                if (lhs.equals("@")|| rhs.equals("#")) {
                    return -1;
                } else if (lhs.equals("#")|| rhs.equals("@")) {
                    return 1;
                } else {
                    //按拼音的首字母来排序
                    return characterParser.getSelling(lhs).substring(0,1).toUpperCase()
                            .compareTo(characterParser.getSelling(rhs).substring(0,1).toUpperCase());
                }
            }
        });

    }

    private void initView() {
        adapter = new SortAdapter(this,list);
        list_view.setAdapter(adapter);
        sidr_bar.setTextView(text_view);
        //设置右侧触摸监听
        sidr_bar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                if(!TextUtils.isEmpty(s) && adapter != null){
                    //该字母首次出现的位置
                    int position = adapter.getPositionForSection(s.charAt(0));
                    if(position != -1){
                        list_view.setSelection(position);
                    }
                }
            }
        });

        edit_text.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     * @param filterStr
     */
    private void filterData(String filterStr){
        List<String> filterDateList = new ArrayList<>();

        if(TextUtils.isEmpty(filterStr)){
            filterDateList = list;
        }else{
            filterDateList.clear();
            for(String s : list){
                if(s.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(s).startsWith(filterStr.toString())){
                    filterDateList.add(s);
                }
            }
        }

        // 排序
        Collections.sort(filterDateList, new Comparator<String>() {

            @Override
            public int compare(String lhs, String rhs) {
                if (lhs.equals("@")|| rhs.equals("#")) {
                    return -1;
                } else if (lhs.equals("#")|| rhs.equals("@")) {
                    return 1;
                } else {
                    //按拼音的首字母来排序
                    return characterParser.getSelling(lhs).substring(0,1).toUpperCase()
                            .compareTo(characterParser.getSelling(rhs).substring(0,1).toUpperCase());
                }
            }
        });
        if(adapter != null)
            adapter.updateListView(filterDateList);
    }

    class SortAdapter extends BaseAdapter implements SectionIndexer {
        private List<String> list = null;
        private Context context;
        public SortAdapter(Context context, List<String> list) {
            this.context = context;
            this.list = list;
        }

        /**
         * 当ListView数据发生变化时,调用此方法来更新ListView
         * @param list
         */
        public void updateListView(List<String> list){
            this.list = list;
            notifyDataSetChanged();
        }

        public int getCount() {
            return this.list.size();
        }

        public Object getItem(int position) {
            return list.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View view, ViewGroup arg2) {
            ViewHolder viewHolder = null;
            if (view == null) {
                viewHolder = new ViewHolder();
                view = LayoutInflater.from(context).inflate(R.layout.indexable_list_item, null);
                viewHolder.text = (TextView) view.findViewById(R.id.text);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.text.setText(list.get(position));
            return view;
        }

        /**
         * 根据ListView的当前位置获取分类的首字母的Char ascii值
         */
        public int getSectionForPosition(int position) {
            return list.get(position).charAt(0);
        }

        /**
         * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
         */
        public int getPositionForSection(int section) {
            for (int i = 0; i < getCount(); i++) {
                String sortStr = list.get(i);
                char firstChar = characterParser.getSelling(sortStr).toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }

            return -1;
        }

        /**
         * 提取英文的首字母，非英文字母用#代替。
         *
         * @param str
         * @return
         */
        private String getAlpha(String str) {
            String sortStr = str.trim().substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortStr.matches("[A-Z]")) {
                return sortStr;
            } else {
                return "#";
            }
        }

        @Override
        public Object[] getSections() {
            return null;
        }

        class ViewHolder {
            TextView text;
        }
    }

    @Override
    public String setTitle() {
        return "SideBar";
    }
}
